import React, { Component } from "react";
import { homeDeng } from "../../../../api/index"
import "./settingColorRGBtiao.less";
import PubSub from 'pubsub-js'
import { meshLog, SPRemove, SPGet, SPSet } from "../../../../config";
import { saveAreaInfor, saveLightInfor, saveGroupSetInfor } from '../../../../utils/homeUtils';
import { PandanRGB, HSLtoHSVtoHSL, SetRGBTiaodate } from '../../../../utils/adminUtils';
import { getOctets2Msg } from '../../../../utils/dataUtils';
import { HSLTORGB, RGBTOSixColor, } from '../../../../utils/adminUtils'
class SettingColorRGBtiao extends Component {
  componentDidMount() {
    let addr = ''
    let item = ''
    let maxTrim1 = ''
    let chackshu2 = ''
    let areaSetx = JSON.parse(SPGet("areaSetx"))
    let eBarWrap = document.getElementById('RGBtiao');
    //获取滑动条
    let eBarCon = eBarWrap.getElementsByClassName('RGBtiaoslide')[0];
    //获取滑动痕迹元素
    let eBarIntotiao = eBarWrap.getElementsByClassName('RGBtiaocontent')[0];
    let areamix = eBarWrap.getElementsByClassName('RGBtiaomix')[0];
    //获取滑块
    let eBarDrag = eBarWrap.getElementsByClassName('RGBtiaobtnkuai')[0];
    //获取文本元素
    let RGBtiaomsg = eBarWrap.getElementsByClassName('RGBtiaomsg')[0];
    // let eBarText = eBarWrap.getElementsByClassName('bar_text')[0];
    //获取最大位置
    //meshLog(areaSetxxx[0]);
    let nMaxx = (eBarCon.offsetWidth - eBarDrag.offsetWidth);
    let rgbshuju = JSON.parse(SPGet("rgbshuju"))
    //这边没有最大的限制
    //  maxTrim1 = rgbshuju.maxTrim
    maxTrim1 = 'FFFF'
    eBarDrag.style.left = nMaxx * (rgbshuju.dim) / 65535 + 'px';
    //修改滑动痕迹宽度
    eBarIntotiao.style.width = nMaxx * (rgbshuju.dim) / 65535 + eBarDrag.offsetWidth / 2 + 'px';
    let maxTrim2 = Math.round((parseInt(maxTrim1, 16)) / 65535 * 100) //16转换成10进制
    let max = maxTrim2 / 100
    let nMax = (eBarCon.offsetWidth - eBarDrag.offsetWidth) * max;
    areamix.style.width = (eBarCon.offsetWidth - eBarDrag.offsetWidth) * max + eBarDrag.offsetWidth + 'px';
    let h = rgbshuju.rgbH
    if (rgbshuju.rgbH == 0) {
      h = parseFloat(SPGet("hslh"))
    }
    let s = 1
    let l = 0.5
    let rgb = HSLTORGB(h, s, l)
    eBarIntotiao.style.background = RGBTOSixColor(rgb)
    //滑块添加拖拽事件
    eBarDrag.addEventListener('mousedown', function (event) {
      //初始化鼠标开始拖拽的点击位置
      let nInitX = event.clientX;
      //初始化滑块位置
      let nInitLeft = this.offsetLeft;
      //meshLog("初始化滑块位置", nInitLeft);
      //页面绑定鼠标移动事件
      document.onmousemove = event => {
        //鼠标移动时取消默认行为，避免选中其他元素或文字
        event.preventDefault();
        //获取鼠标移动后滑块应该移动到的位置
        let nX = event.clientX - nInitX + nInitLeft;
        //限制滑块最大移动位置
        if (nX >= nMax) {
          nX = nMax;
        }
        //限制滑块最小移动位置
        if (nX <= 0) {
          nX = 1;
        }
        //修改滑块位置（因为用的是箭头函数，所以this还是指向滑块）
        this.style.left = nX + 'px';
        //修改滑动痕迹宽度
        eBarIntotiao.style.width = nX + this.offsetWidth / 2 + 'px';
        //修改文本数值eBarText.innerHTML = Math.ceil(nX / nMax * 100) / 10;
        RGBtiaomsg.innerText = Math.ceil(nX / (nMaxx) * 100);
        // meshLog('实时的参数值', Math.ceil(nX / nMax * 100));
      };
      //鼠标松开绑定事件，取消页面上所有事件
      document.onmouseup = async function (event) {
        let rgbpanduan = JSON.parse(SPGet("rgbpanduan"))
        let areadate = PandanRGB(rgbpanduan)
        document.onmousemove = null;
        document.onmouseup = null;
        meshLog("settingColorRGBtiao.js,85行,滑动最终的值", RGBtiaomsg.innerText);
        const values = RGBtiaomsg.innerText;
        const token = SPGet('token')
        const email = SPGet('email')
        const meshUUID = SPGet('meshUUID')
        const addrs = areadate[1].substring(2, 4) + areadate[1].substring(0, 2);
        const opCode = "824D";
        let value1 = Math.ceil(values * 65535 / 100);
        const value = getOctets2Msg(value1);
        let result = await homeDeng(token, email, meshUUID, addrs, opCode, value);
        const dimx = Math.round(RGBtiaomsg.innerText / 100 * 65535)
        const { ctl_status } = result;
        if (ctl_status == 0) {
          // meshLog("dimx", dimx);
          //修改localStorage上areaSetx的数据
          let areaitem;
          for (let index = 0; index < areaSetx.length; index++) {
            if (areaSetx[index].areaNo == areadate[1]) {
              areaitem = areaSetx[index]
            }
          }
          //修改亮度的时候，在rgb状态下的hsl的值的也要修改的
          if (areaitem.rgbH > 0) {
            let hslh = areaitem.rgbH
            let hsls = areaitem.rgbS
            let hsll = areaitem.rgbL
            let hsl = HSLtoHSVtoHSL(hslh, hsls, hsll, dimx)
            areaitem.dim = dimx
            areaitem.rgbH = hsl[0]
            areaitem.rgbS = hsl[1]
            areaitem.rgbL = hsl[2]
            saveAreaInfor(areaitem)
          } else {
            areaitem.dim = dimx
            //meshLog('areaitem', areaitem);
            saveAreaInfor(areaitem)
          }
          //修改localStorage上deviceSetx的数据
          let deviceSetx = JSON.parse(SPGet("deviceSetx"));
          let devSetItem = [];
          //查询属于这个areaNo的 device
          devSetItem = deviceSetx.filter((item) => {
            if (item.areaNo == areadate[1] && item.isOnline == '01') {
              if (item.rgbH > 0) {
                let hslh = item.rgbH
                let hsls = item.rgbS
                let hsll = item.rgbL
                let hsl = HSLtoHSVtoHSL(hslh, hsls, hsll, dimx)
                item.dim = dimx
                item.rgbH = hsl[0]
                item.rgbS = hsl[1]
                item.rgbL = hsl[2]
              } else {
                item.dim = dimx
              }
              return item
            }
          })
          // meshLog('devSetItem', devSetItem);
          saveLightInfor(devSetItem)
          //查询属于这个areaNo的 subgroup
          let groupSetx = JSON.parse(SPGet("groupSetx"));
          let groupSetItem = [];
          groupSetItem = groupSetx.filter((item) => {
            if (item.areaNo == areadate[1] && item.isOnline == '01') {
              if (item.rgbH > 0) {
                let hslh = item.rgbH
                let hsls = item.rgbS
                let hsll = item.rgbL
                let hsl = HSLtoHSVtoHSL(hslh, hsls, hsll, dimx)
                item.dim = dimx
                item.rgbH = hsl[0]
                item.rgbS = hsl[1]
                item.rgbL = hsl[2]
              } else {
                item.dim = dimx
              }
              return item
            }
          })
          // meshLog('groupSetItem', groupSetItem);
          saveGroupSetInfor(groupSetItem)
          // meshLog("传到home页面上需要展示右边数据的组", item);
          PubSub.publish('data', areaitem)
          PubSub.publish('areadata', areaitem)//传到组的亮度那边
        }
      }
    });
    //滑动条添加点击事件
    eBarCon.addEventListener('click', async function (event) {
      //设置滑动条位置
      let nLeft = this.offsetLeft;
      //获取有定位的父元素
      let eParent = this.offsetParent;
      //循环所有有定位的父元素
      while (eParent) {
        //添加定位父元素offsetLeft值，用于准确定位滑动条与页面左侧的距离
        nLeft += eParent.offsetLeft;
        //再次获取父元素外的定位父元素
        eParent = eParent.offsetParent;
      }
      //计算滑块位置
      let nX = event.clientX - nLeft;
      //修改滑块位置
      if (nX >= nMax) {
        nX = nMax;
      }
      //限制滑块最小移动位置
      if (nX <= 0) {
        nX = 1;
      }
      eBarDrag.style.left = nX + 'px';
      // meshLog("clientX", event.clientX);
      // meshLog("nLeft", nLeft);
      // meshLog("nX", nX);
      //修改滑动痕迹宽度
      eBarIntotiao.style.width = nX + eBarDrag.offsetWidth / 2 + 'px';
      //修改文本数值eBarText.innerHTML = Math.ceil(nX / nMax * 100) / 10
      RGBtiaomsg.innerText = Math.ceil(nX / nMaxx * 100);
      //meshLog("点击的最终值", RGBtiaomsg.innerText)
      SetRGBTiaodate(RGBtiaomsg.innerText)
    });
    //接收RGB页面给我返回的V来修改组里的亮度和灯的亮度
    PubSub.unsubscribe("RGBV")
    PubSub.subscribe('RGBV', async (msg, data) => {
      let rgbshuju = JSON.parse(SPGet("rgbshuju"))
      let h = rgbshuju.rgbH
      if (rgbshuju.rgbH == 0) {
        h = parseFloat(SPGet("hslh"))
      }
      // meshLog('rgbshuju', rgbshuju);
      let s = 1
      let l = 0.5
      let rgb = HSLTORGB(h, s, l)
      meshLog('rgbshuju', rgb);
      //eBarIntotiao.style.background = RGBTOSixColor(rgb)
      nMaxx = (eBarCon.offsetWidth - eBarDrag.offsetWidth);
      eBarDrag.style.left = nMaxx * data + 'px';
      //修改滑动痕迹宽度
      eBarIntotiao.style.width = nMaxx * data + eBarDrag.offsetWidth / 2 + 'px';
      //修改文本数值eBarText.innerHTML = Math.ceil(nX / nMax * 100) / 10
      RGBtiaomsg.innerText = Math.ceil(data * 100);
      const values = Math.ceil(data * 100)
      const token = SPGet('token')
      const email = SPGet('email')
      const meshUUID = SPGet('meshUUID')
      const addrs = addr;
      const opCode = "824D";
      const value = values;
      let result = await homeDeng(token, email, meshUUID, addrs, opCode, value);
      const dimx = Math.ceil((RGBtiaomsg.innerText) / 100 * 65535)
      const { ctl_status } = result;
      if (ctl_status == 0) {
        // meshLog("dimx", dimx);
        let areaitem;
        for (let index = 0; index < areaSetx.length; index++) {
          if (areaSetx[index].areaNo == addr) {
            areaitem = areaSetx[index]
          }
        }
        areaitem.dim = dimx
        //meshLog('areaitem', areaitem);
        saveAreaInfor(areaitem)
        //修改localStorage上deviceSetx的数据
        let deviceSetx = JSON.parse(SPGet("deviceSetx"));
        let devSetItem = [];
        //查询属于这个areaNo的 device
        devSetItem = deviceSetx.filter((item) => {
          if (item.areaNo == addr && item.isOnline == '01') {
            item.dim = dimx
            return item
          }
        })
        // meshLog('devSetItem', devSetItem);
        saveLightInfor(devSetItem)
        //查询属于这个areaNo的 subgroup
        let groupSetx = JSON.parse(SPGet("groupSetx"));
        let groupSetItem = [];
        groupSetItem = groupSetx.filter((item) => {
          if (item.areaNo == addr && item.isOnline == '01') {
            item.dim = dimx
            return item
          }
        })
        // meshLog('groupSetItem', groupSetItem);
        saveGroupSetInfor(groupSetItem)
        PubSub.publish('data', item)//传到页面上需要展示右边数据的组 其修改亮度
        PubSub.publish('areadata', item)//修改亮度之后也要反馈给area让其修改亮度
      }
    });
    //接收RGB页面给我返回的修改背景颜色 '#' + ((1 << 24) + (parseInt(rgb[0] * 255) << 16) + (parseInt(rgb[1] * 255) << 8) + parseInt(rgb[2] * 255)).toString(16).slice(1)
    // PubSub.unsubscribe("RGBtiaobackColor")
    PubSub.subscribe('RGBtiaobackColor', async (msg, data) => {
      meshLog('settingColorRGBtiao.js,277 RGBtiaobackColor ',);
      let h = parseFloat(SPGet("hslh"))
      let s = 1
      let l = 0.5
      let rgb = HSLTORGB(h, s, l)
      eBarIntotiao.style.background = RGBTOSixColor(rgb)
      eBarIntotiao.style.background = '#' + ((1 << 24) + (parseInt(rgb[0] * 255) << 16) + (parseInt(rgb[1] * 255) << 8) + parseInt(rgb[2] * 255)).toString(16).slice(1)
    });
  }
  render() {
    return (
      <div style={{ float: "left", marginTop: 20 }}>
        <div className="RGBtiao" id='RGBtiao'>
          <div className="RGBtiaomsg" style={{}}  >0</div>
          <div className="RGBtiaomix" style={{ width: 250, height: 20, marginTop: -23 }} >
          </div>
          <div className="RGBtiaoslide" style={{ marginTop: -23 }}   >
            <div className="RGBtiaocontent" >
            </div>
          </div>
          <div className="RGBtiaobtnkuai">
          </div>
        </div>
      </div >
    );
  }
};
export default SettingColorRGBtiao;
